/**
 * Created by SN on 2018/2/6.
 * http配置
 */
import axios from 'axios'
import router from './routes'
import { Message } from 'element-ui'

// axios 配置
axios.defaults.timeout = 30000;

// 请求拦截器
axios.interceptors.request.use(
    config => {
        if(sessionStorage.getItem("token")) {
            config.headers['token'] = sessionStorage.getItem("token");
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

// http response 拦截器
axios.interceptors.response.use(
    response => {
        console.log("response.use.response")
        return response;
    },
    error => {
        debugger
        console.log("response.use.error")
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 401 清除token信息并跳转到登录页面
                    sessionStorage.removeItem("token");
                    router.replace({
                        path: 'login',
                        query: {redirect: router.currentRoute.fullPath}
                    });
                    break;
                case 403:
                    Message({
                        message: '你没有此操作权限',
                        type: 'error'
                    })
                    break;
                case 301:
                    Message({
                        message: '系统内部异常',
                        type: 'error'
                    })
            }
        }
        return Promise.reject(error.response.data)
    }
);

export default axios;